package tuvienna.jade.table;

import tuvienna.jade.Constants;
import jade.core.AID;
import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;

/**
 * Handling the deregistration of participants on tables
 */
public class DeregistrationServiceBehaviour extends CyclicBehaviour {

	private static final long serialVersionUID = 4299417511842916808L;
	private TableAgent tableAgent;

	private MessageTemplate mt;
	
	public DeregistrationServiceBehaviour(TableAgent tableAgent) {
		this.tableAgent = tableAgent;
		mt = MessageTemplate.MatchConversationId(getConversationID());
	}

	public void action() {
		ACLMessage msg = tableAgent.receive(mt);
		if (msg != null) {
			// Message received. Process it
			ACLMessage reply = msg.createReply();
			AID participantAID = msg.getSender();
			// last participant may not leave table;
			boolean canDeregister = tableAgent.lastParticipantCanDeregister || tableAgent.getParticipantsSize() > 1;
			if (!canDeregister || !tableAgent.hasParticipant(participantAID)) {
				//System.out.println("Participant "+participantAID.getLocalName()+" is not registered on table "+tableAgent.getLocalName());					
				reply.setPerformative(ACLMessage.REFUSE);
			}
			else {
				reply.setPerformative(ACLMessage.AGREE);
				tableAgent.removeParticipant(participantAID);
				//System.out.println("Participant "+participantAID.getLocalName()+" deregistered from table "+tableAgent.getLocalName());
			}
			tableAgent.send(reply);
		} else {
			block();
		}
	}

	protected String getConversationID() {
		return Constants.DEREGISTRATION_REQUEST;
	}
	
}
